package homework.test1.Dao;

import homework.test1.Domain.User;

import java.io.*;
import java.util.ArrayList;

public class LoginDao {
    private static ArrayList<User> list = new ArrayList<>();

    static {
        readUser(list);
    }

    private static void readUser(ArrayList<User> list){
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("Day13\\src\\homework\\test1\\Dao\\user.txt"));
            byte [] bytes = new byte[1024*1024];
            int len = bis.read(bytes);
            String userStr = new String(bytes,0,len);
            bis.close();

            String [] userLine = userStr.split(System.lineSeparator());
            for (String s : userLine) {
                String [] userArr = s.split(",");
                int age = Integer.parseInt(userArr[1]);
                User user = new User(userArr[0],age,userArr[2],userArr[3],userArr[4]);
                list.add(user);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public int isExist(String name) {
        int index = -1;
        for (int i = 0; i < list.size(); i++) {
            User user = list.get(i);
            if(user.getUsername().equals(name)){
                index = i;
                return index;
            }
        }
        return index;
    }

    public boolean addUser(User user) {
        list.add(user);
        saveUser(list);
        return true;
    }

    private void saveUser(ArrayList<User> list){
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream("Day13\\src\\homework\\test1\\Dao\\user.txt"));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        try {
            for (User user : list) {bos.write(user.toString().getBytes());bos.write("\r\n".getBytes());
            }
        } catch (IOException e) {
            System.out.println("储存出错");
        }finally {
            try {
                bos.close();
            } catch (IOException e) {
                System.out.println("关闭出错");
            }
        }

    }

    public ArrayList<User> find() {
        return list;
    }

    public User getUser(int index) {
        return list.get(index);
    }
}
